﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using StockMatch.Service;
using StockMatch.Service.Entity;
using Titan;

namespace StockMatch.WebSite.Areas.Admin.Controllers
{
    /// <summary>
    /// 管理员管理
    /// </summary>
    public class AdminUserController :AdminControllerBase
    {
        #region 管理员：编辑

        public ActionResult Index(int? page,string kw,int? dept)
        {
            ViewBag.Menu = "AdminUser";
            ViewBag.Tag = "Index";

            int pageIndex=page==null?1 :(int)page;

            #region 查询列表
            var query = new QueryExpression();
            query.EntityType = typeof(AdminUser);
            query.Select(AdminUser_.ALL);
            if (!string.IsNullOrEmpty(kw))
            {
                query.Wheres.Add(AdminUser_.AdminUserName.TLike(kw));
            }
            if (dept != null && dept > 0) {
                query.Wheres.Add(AdminUser_.AdminUserDepart.TEqual(dept));
            }
            query.OrderBys.Add(AdminUser_.AdminUserId.Desc);
            query.PageIndex = pageIndex;
            query.PageSize = 10;
            query.ReturnMatchedCount = true;
            var adminUsers = new AdminUsers();
            adminUsers = ServiceManager.AdminUserService.GetUsers(query);

            #endregion

            ViewBag.PageIndex = pageIndex;
            ViewBag.TotalCount = adminUsers.TotalCount;
            ViewBag.Keyword = kw;
            ViewBag.DepartId = dept==null?0 :(int)dept;
            return View(adminUsers);
        }

        #endregion

        #region 管理员：编辑

        [HttpGet]
        public ActionResult Edit(string md,int? id,int page,string kw, int dept) {
            ViewBag.Menu = "AdminUser";
            ViewBag.Tag = "Edit";

            AdminUser adminUser = new AdminUser();
            if (md == "update" && id != null)
            {
                adminUser =ServiceManager.AdminUserService.GetUser((int)id);
            }

            #region 获取部门列表
            /*
            QueryExpression query = new QueryExpression();
            query.EntityType = typeof(AdminUser);
            query.Select(Classes_.ClassesId, Classes_.ClassesName);
            query.Where(Classes_.ClassesParentId.TEqual("000"));
            var classesList = ServiceManager.ClassesService.GetClassesList(query).Items;

            //若是修改，则设置下拉选项中的相应值被选中
            if (classesList.Count > 0 && md == "update")
            {
                if (classes.ClassesParentId.Length == 3)
                {
                    if (classesList.Count(p => p.ClassesId == classes.ClassesParentId) > 0)
                    {
                        classesList.Find(p => p.ClassesId == classes.ClassesParentId).ClassesMark = "1";
                    }
                }
            }

            ViewData["classesList"] = classesList;
            */
            #endregion

            ViewBag.Operation = md == "update" ? "update" : "add";//记录修改、新增代码
            ViewBag.PageIndex = page;
            ViewBag.Keyword = kw;
            ViewBag.DepartId = dept;
            ViewBag.Operation = md;
            return View(adminUser);
        }

        [HttpPost]
        public ActionResult Edit(string md, AdminUser adminUser,int page, string kw, int dept)
        {
            var rs = false;
            adminUser.AdminUserName = adminUser.AdminUserName.ToLower();
            adminUser.UpdateTime = DateTime.Now;
            adminUser.LastUpdateAdminUserId = CurrentAdminUser.AdminUserId;//最后修改用户
            if (md == "add")
            {
                adminUser.AddTime = DateTime.Now;
                adminUser.AdminUserState = 0;
                adminUser.AdminPassword = Encryption.GetMD5HashHex(adminUser.AdminPassword.ToLower());
                rs = ServiceManager.AdminUserService.Insert(adminUser);
                page = 1; kw = null;
            }
            else if (md == "update") {
                var updateproerty = new PropertyExpression[] {
                    AdminUser_.AdminUseEmail,
                    AdminUser_.AdminUsePhone,
                    AdminUser_.AdminUseQQ,
                    AdminUser_.AdminUserDepart,
                    AdminUser_.AdminUserName,
                    AdminUser_.AdminUseSex,
                    AdminUser_.AdminUseTel,
                    AdminUser_.AdminUseTrueName,
                    AdminUser_.UpdateTime,
                    AdminUser_.LastUpdateAdminUserId
                };
                rs = ServiceManager.AdminUserService.Update(adminUser, updateproerty);
            }

            var showMessage = (md == "add" ? "添加" : "修改") + (rs ? "成功" : "失败");
            if (!rs)
            {
                return Content("<script>alert('管理员" + showMessage + "');location.href='" + Url.Action("Edit",(new {md = md, id=adminUser.AdminUserId, page = page, kw = kw, dept = dept })) + "'</script>", "text/html");
            }
            else
            {
                return Content("<script>alert('管理员" + showMessage + "');location.href='" + Url.Action("Index", (new { page = page,kw = kw, dept =dept})) + "'</script>", "text/html");
            }
        }

        #endregion

        #region 管理员：删除
        public ActionResult Delete(int id, int page,string kw, int dept)
        {
            if (id < 1)
            {
                throw new Exception("删除操作失败，ID为0");
            }
            var rs = ServiceManager.AdminUserService.Delete(id);
            //若删除失败，需要提示
            if (!rs)
            {
                return Content("<script>alert('管理员删除失败');location.href='" + Url.Action("Index", (new { page = page,kw = kw,dept =dept})) + "'</script>", "text/html");
            }
            return RedirectToAction("Index", new { page = page,kw = kw, dept = dept });
        }

        #endregion

    }
}
